import React, { useEffect, useState } from "react";
import { message, Switch } from "antd"; // 引入 Switch 组件
import UserTable from "../userTable"; // 引入公共表格组件
import { getAllUsersApi } from "../../../api/user"; // 引入获取所有用户的 API
import { getUserTypeStr } from "../../../utils/userUtils";
function AllUser() {
  const [data, setData] = useState([]); // 用户数据
  const [loading, setLoading] = useState(false); // 加载状态

  // 表格列配置
  const columns = [
    {
      title: "序号",
      key: "index",
      render: (text, record, index) => index + 1, // 渲染序号
    },
    { title: "用户名", dataIndex: "username", key: "username" },
    { title: "真实姓名", dataIndex: "real_name", key: "real_name" },
    {
      title: "角色",
      dataIndex: "role",
      key: "role",
      render: (role) => getUserTypeStr(role),
    },
    { title: "邮箱", dataIndex: "email", key: "email" },
    { title: "手机号", dataIndex: "phone", key: "phone" },
    {
      title: "是否激活",
      dataIndex: "is_active",
      key: "is_active",
      render: (isActive, record) => (
        <Switch
          checked={isActive} // 根据 isActive 状态设置开关状态
          onChange={(checked) => handleActivationChange(record.id, checked)} // 处理开关切换
        />
      ),
    },
  ];

  // 处理激活状态切换
  const handleActivationChange = async (userId, isActive) => {
    console.log(`用户ID: ${userId}, 激活状态: ${isActive}`);
    // 在这里可以调用 API 更新用户激活状态
    // await updateUserActivationApi(userId, isActive);
  };

  useEffect(() => {
    const fetchUsers = async () => {
      setLoading(true);
      try {
        const response = await getAllUsersApi();

        // 确保每个用户都有唯一的 key
        const usersWithKey = response.users.map((user, index) => ({
          ...user,
          key: user.id || index, // 如果没有 id，则使用索引作为 key
        }));

        setData(usersWithKey); // 设置用户数据
      } catch (err) {
        message.error("获取用户列表失败：" || err.data?.detail);
      } finally {
        setLoading(false);
      }
    };

    fetchUsers();
  }, []);

  return (
    <div>
      <h2>所有用户</h2>
      <UserTable columns={columns} data={data} loading={loading} />
    </div>
  );
}

export default AllUser;
